function wf = trainNeuralNetwork(X, wi, b, tol, epoch)
% trainNeuralNetwork
%   This function trains a neural network with a given set
%   of patterns (X), an initial weiths (wi), the expected 
%   solution for each pattern (b). An exitation function (g)
%   and its derivative function (dg) and returns the array of matrixes
%	of the trained weigths for the neural network (wf)
%   
%   Input
%
%   X:  The set of patterns.
%   wi: The array of matrixes of initial weight for each layer. 
%   b:  The expected solution for each pattern.
%   epoch: number of epochs
%
%   Output:
%   wf: The array of matrixes of the trained weigths.

    global ETA A_ETA_ADAP B_ETA_ADAP;

    wf = wi;
    previousError = 0;
    errores = [];
    epocas = [];    
    for t = 1:epoch,
        for x = 1:length(X(1,:))
            backPropData = feedForward(X(:,x), wf, b(x));
            wf = backpropagation(wf, backPropData, X(:,x));
        end
        err = errorFunction(X, wf, b);
        % ETA ADAPTATIVO
        if previousError ~= 0
            if err - previousError < 0
                ETA = ETA + A_ETA_ADAP;
            elseif err - previousError > 0
                ETA = ETA - B_ETA_ADAP*ETA;
            end
        end
        previousError = err;
        X = shufflePatterns(X, b);
        b = X(length(X(:,1)),:);
        X = X(1:length(X(:,1))-1,:);
        disp('Error: ');
        disp(err);
        if(err < tol)
            break;
        end
        if mod(t,100) == 0
           errores = [errores, err];
           epocas = [epocas, t];
        end        
    end
    plot(epocas, errores, '-');
    disp('Epocas procesadas:');
    t
end
